package com.liu.queue.handler;

import com.alibaba.fastjson.JSON;
import com.liu.message.impl.ResponseMessage;
import com.liu.queue.message.PullMessage;
import com.liu.queue.storage.StorageProvider;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @param
 * @BelongsProject: QueueDemo2
 * @BelongsPackage: com.liu.queue.handlerPush
 * @author: L
 * @Date: 2023/10/16 9:31
 * @return
 */

@Slf4j
public class PullOrdinaryRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        log.info("HTTP消息");
        // 获取请求体
        String string = fullHttpRequest.content().toString(CharsetUtil.UTF_8);
        PullMessage message = JSON.parseObject(string, PullMessage.class);
        // 返回值为List<String>
        ResponseMessage responseMessage = StorageProvider.HandlerPull(message);
        String jsonString = JSON.toJSONString(responseMessage);
        // 经过HttpServerCodec处理器的处理后消息被封装为FullHttpRequest对象
        // 创建完整的响应对象
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,
                Unpooled.copiedBuffer(jsonString, CharsetUtil.UTF_8));
        // 设置头信息
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        // 响应写回给客户端
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    //解析方法，将字符串解析为一个Map结构
    private Map<String, String> getRequestParams(FullHttpRequest request) {
        HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);
        List<InterfaceHttpData> httpPostData = decoder.getBodyHttpDatas();
        Map<String, String> params = new HashMap<>();

        for (InterfaceHttpData data : httpPostData) {
            if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                MemoryAttribute attribute = (MemoryAttribute) data;
                params.put(attribute.getName(), attribute.getValue());
            }
        }
        return params;
    }

}
